package com.junchao.peng.config;

import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author dell
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    /**
     * 匹配url 中的资源映射
     */
    private String resourceHandler = "/file/**";
    /**
     * 上传文件保存的本地目录
     */
    private String location;
    /**
     * 获取当前运行系统环境
     */
    private static final String OS_NAME = System.getProperty("os.name").toLowerCase();

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").
                        allowedOrigins("*").
                        allowedHeaders("*").
                        allowedMethods("POST", "GET", "DELETE", "PUT", "HEAD", "OPTIONS").
                        allowCredentials(false).
                        exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L);
            }
        };
    }

    /**
     * 配置静态资源映射
     * @param registry 1
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //匹配到resourceHandler,将URL映射至location,也就是本地文件夹
        if (OS_NAME.contains("windows")){
            //运行环境为 windows
            LoggerFactory.getLogger(getClass()).info("windows");
            location = "D:/localhostTestImageS/uploadImageS/";
        }else {
            //运行环境为 linux
            LoggerFactory.getLogger(getClass()).info("linux");
            location = "/home/Project/";
        }
        registry.addResourceHandler(resourceHandler).addResourceLocations("file:///" + location);
    }
}
